"""
Case Type   : 资源池化-多节点写入
Case Name   : 备机在事务中执行INSERT/DELETE/UPDATE语句并提交
Create At   : 2024/04/30
Owner       : zhengxue
Description :
    1.修改enable_remote_execute参数值为on
    2.创建测试表
    3.备机在事务中执行INSERT/DELETE/UPDATE语句并提交
    4.查看日志打印
    5.环境清理，恢复参数
Expect      :
    1.修改成功
    2.执行成功
    3.执行成功
    4.日志记录建立连接、转发给主机、接受执行结果等libpqsw信息
    5.环境清理成功，恢复参数成功
Pre-operation:
    1.在conf/macro.yml中配置PG_LOG_PATH为数据库pg_log目录,对应用例中的macro.PG_LOG_PATH
History     :
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

Primary_SH = CommonSH('PrimaryDbUser')


class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_node = Node('Standby1DbUser')
        self.standby_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.table_name = 't_write_transfer_case0010'
        self.new_log_dir = os.path.join(macro.PG_LOG_PATH,
                                        'pg_log_write_transfer_case0010')
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.assertEquals('', shell_msg, '删除目录失败')

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.logger.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, f'执行失败:{step1}')
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'执行失败:{step1}')
        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.logger.info(status)
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_excute, 'on', f'执行失败:{step1}')
        result = self.standby_sh.execute_gsguc('reload',
                                               self.constant.GSGUC_SUCCESS_MSG,
                                               f'{self.log_statement}=all')
        self.assertTrue(result, f'执行失败:{step1}')
        show_log_statement = self.common.show_param(self.log_statement)
        self.assertEquals(show_log_statement, 'all', f'执行失败:{step1}')
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.new_log_dir}'", single=True)
        self.assertTrue(result, f'执行失败:{step1}')
        show_log_statement = self.common.show_param(self.log_statement)
        self.assertEquals(show_log_statement, 'all', f'执行失败:{step1}')
        show_log_directory = self.common.show_param(self.log_directory)
        self.assertEquals(show_log_directory, self.new_log_dir, f'执行失败:{step1}')

        step2 = "-----step2:创建测试表;expect:执行成功-----"
        self.logger.info(step2)
        sql_cmd = f"drop table if exists {self.table_name} cascade;" \
                  f"create table {self.table_name}(" \
                  f"id int,name varchar(20)) with(segment=on);"
        sql_msg = self.standby_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS,
                      sql_msg, f'执行失败:{step2}')

        step3 = "-----step3:备机在事务中执行INSERT/DELETE/UPDATE语句" \
                "并提交;expect:执行成功-----"
        self.logger.info(step3)
        sql_cmd = f'''start transaction;
        insert into {self.table_name} values(generate_series(1,10), 'test');
        update {self.table_name} set name='software' where id = 3;
        delete from {self.table_name} where id=5;
        commit;
        select pg_sleep(10);
        select * from {self.table_name};'''
        sql_msg = self.standby_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      sql_msg, f'执行失败:{step3}')
        self.assertIn(self.constant.INSERT_SUCCESS_MSG,
                      sql_msg, f'执行失败:{step3}')
        self.assertIn(self.constant.UPDATE_SUCCESS_MSG,
                      sql_msg, f'执行失败:{step3}')
        self.assertIn(self.constant.DELETE_SUCCESS_MSG,
                      sql_msg, f'执行失败:{step3}')
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, sql_msg,
                      f'执行失败:{step3}')
        self.assertIn("  1 | test\n  2 | test\n  4 | test\n  6 | test\n  "
                      "7 | test\n  8 | test\n  9 | test\n 10 | test\n  "
                      "3 | software", sql_msg, f'执行失败:{step3}')
        time.sleep(2)

        step4 = "-----step4:查看日志打印;expect:日志记录建立连接、" \
                "转发给主机、接受执行结果等libpqsw信息-----"
        self.logger.info(step4)
        shell_cmd = f"ls -t {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        logfile = os.path.join(self.new_log_dir, shell_msg.split()[-1])
        self.logger.info(logfile)
        shell_cmd = f"cat {logfile} "
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.assertIn('transaction status change, current commit '
                      'status:begin', shell_msg, f'执行失败:{step4}')
        self.assertIn('Connecting to remote server',
                      shell_msg, f'执行失败:{step4}')
        self.assertIn(f'libpq send sql at my side as well:START TRANSACTION',
                      shell_msg, f'执行失败:{step4}')
        self.assertIn(f'Q: portal=INSERT', shell_msg, f'执行失败:{step4}')
        self.assertIn(f'Q: portal=UPDATE', shell_msg, f'执行失败:{step4}')
        self.assertIn(f'Q: portal=DELETE', shell_msg, f'执行失败:{step4}')
        self.assertIn(f'transaction status change, current commit status:end',
                      shell_msg, f'执行失败:{step4}')
        self.assertIn(f'libpq send sql at my side as well:COMMIT', shell_msg,
                      f'执行失败:{step4}')

    def tearDown(self):
        step5 = "-----step5:环境清理，恢复参数;expect:环境清理成功，恢复参数成功-----"
        self.logger.info(step5)
        drop_cmd = f"drop table if exists {self.table_name};"
        drop_msg = self.standby_sh.execut_db_sql(drop_cmd)
        self.logger.info(drop_msg)
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.logger.info(status)
        status = Primary_SH.check_cluster_core_status(status, wait_times=600)
        self.logger.info(status)
        restart_res = self.standby_sh.restart_db_cluster()
        recovery = Primary_SH.exec_cm_ctl(mode='switchover', param='-a')
        self.logger.info(recovery)
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        result2 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.log_dir_default}'", single=True)
        show_log_statement = self.common.show_param(self.log_statement)
        show_log_directory = self.common.show_param(self.log_directory)
        self.logger.info("-----断言teardown-----")
        self.assertIn(self.constant.TABLE_DROP_SUCCESS,
                      drop_msg, f'执行失败:{step5}')
        self.assertTrue(result1, f'执行失败:{step5}')
        self.assertTrue(restart_res, f'执行失败:{step5}')
        self.assertIn(self.constant.cm_switchover_success_msg, recovery,
                      '执行失败' + step5)
        self.assertEquals(show_remote_excute, self.remote_excute_default,
                          f'执行失败:{step5}')
        self.assertTrue(result2, f'执行失败:{step5}')
        self.assertTrue(result3, f'执行失败:{step5}')
        self.assertEquals(show_log_statement, self.log_statement_default,
                          f'执行失败:{step5}')
        self.assertEquals(show_log_directory, self.log_dir_default,
                          f'执行失败:{step5}')
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
